//
//  GameTableViewController.m
//  VEW
//
//  Created by lanou3g on 15/7/24.
//  Copyright (c) 2015年 Y团. All rights reserved.
//

#import "GameTableViewController.h"
#import "BigImageTableViewCell.h"
#import "NomalModel.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "AFHTTPRequestOperationManager.h"
#define BigImage @"cell"
#import "DetailViewController.h"
#import "HomeModel.h"
@interface GameTableViewController ()
@property (nonatomic ,strong) NSMutableArray * array;

@property (nonatomic ,strong) NSMutableArray * moreArray;

@property (nonatomic ,assign) NSInteger  pageNum;

@property (nonatomic, strong) NSString *url;

@property (nonatomic ,assign) BOOL isRefresh;
@end

@implementation GameTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView registerClass:[BigImageTableViewCell class] forCellReuseIdentifier:BigImage];
    
    self.url = @"http://api.m.jiemian.com/article/cate/294.json";
    self.array = [NSMutableArray array];
    self.pageNum = 1;
    
    [self data];
    [self setupRefresh];
    
    
    UIImage *leftButtonImage=[UIImage imageNamed:@"返回"];
    
    leftButtonImage=[leftButtonImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithImage:leftButtonImage style:UIBarButtonItemStyleDone target:self action:@selector(presentRightMenuViewController:)];
}

-(void)setupRefresh
{
    //下拉刷新
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    
    [self.tableView headerBeginRefreshing];
    
    
    //上拉加载跟多(进入刷新状态就会调用self的footerRefreshing)
    
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    
}



//下拉刷新
- (void)headerRereshing
{
    _pageNum = 1;
    self.isRefresh = NO;
    [self data];
    [self.tableView headerEndRefreshing];
    
    
}



//上拉加载
- (void)footerRereshing
{
    _pageNum ++;
    self.isRefresh = YES;
    [self data];
    [self.tableView footerEndRefreshing];
}


-(void)data
{
    // 网络请求
    AFHTTPRequestOperationManager * manager= [AFHTTPRequestOperationManager manager];
    NSString *url = [self.url stringByAppendingString:[NSString stringWithFormat:@"?&page=%ld",self.pageNum]];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (!self.isRefresh) {
            [self.array removeAllObjects];
        }
        NSDictionary *dic = responseObject[@"result"];
        NSArray *array1 =dic[@"rst"];
        for (NSDictionary *dic1 in array1) {
            NomalModel * normal = [NomalModel new];
            normal.title = dic1[@"title"];
            normal.MyID = dic1[@"id"];
            normal.publishTime = dic1[@"publishtime"];
            normal.comment = dic1[@"comment"];
            normal.photo = dic1[@"l_image"];
            [self.array addObject:normal];
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    [self.tableView reloadData];
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    // Return the number of rows in the section.
    return self.array.count;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NomalModel * normal =self.array[indexPath.row];
    
    
    BigImageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:BigImage forIndexPath:indexPath];
    // 给cell赋值
    cell.titleLabel.text = normal.title;
    cell.timeLabel.text =  [self timeFormatted:[normal.publishTime integerValue]];
    cell.commentLabel.text = [NSString stringWithFormat:@"评论(%@)", normal.comment];
    NSURL *url = [NSURL URLWithString:normal.photo];
    [cell.picImageView sd_setImageWithURL:url];
    
    cell.titleLabel.frame = CGRectMake(10, CGRectGetMaxY(cell.picImageView.frame)+10, CGRectGetWidth(cell.picImageView.frame), [BigImageTableViewCell stringHeight:normal.title]);
    cell.timeLabel.frame =CGRectMake(10, CGRectGetMaxY(cell.titleLabel.frame)+10, CGRectGetWidth(cell.titleLabel.frame)-100, 16);
    cell.commentLabel.frame = CGRectMake(CGRectGetWidth([[UIScreen mainScreen]bounds])-70 , CGRectGetMaxY(cell.titleLabel.frame)+10, 60 , 16);
    
    return cell;
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NomalModel * normal =self.array[indexPath.row];
    return 270+ [BigImageTableViewCell stringHeight:normal.title];
}


// 将秒数转化成日期
- (NSString *)timeFormatted:(long long)totalSeconds
{
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:totalSeconds];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM/dd HH:mm:ss"];
    NSString *showtimeNew = [formatter stringFromDate:date];
    
    return showtimeNew;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 刚选中又马上取消选中，格子不变色
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UIViewController *vc = [[UIViewController alloc]init];
    vc.view.backgroundColor = [UIColor yellowColor];
    
    DetailViewController *detailVC = [DetailViewController new];
    
    HomeModel *home = [HomeModel new];
    
    home = self.array[indexPath.row];
    
    detailVC.homeData = home;
    
    detailVC.hidesBottomBarWhenPushed=YES;
    
    [self.navigationController pushViewController:detailVC animated:YES];
    
    
}

/*
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
    
    // Configure the cell...
    
    return cell;
}
*/

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
